/**
 * @description:
 * @author: asd
 * @time: 2022/10/11 16:15
 */
public class DiningPhilosophers {

    public static void main(String[] args) {
        Philosophers p1 = new Philosophers(0);
        Philosophers p2 = new Philosophers(1);
        Philosophers p3 = new Philosophers(2);
        Philosophers p4 = new Philosophers(3);
        Philosophers p5 = new Philosophers(4);
        new Thread(p1).start();
        new Thread(p2).start();
        new Thread(p3).start();
        new Thread(p4).start();
        new Thread(p5).start();
    }
}

    class Philosophers implements Runnable{
        public int index;
        public static Object[] chops = new Object[]{1, 1, 1, 1, 1};
        public Philosophers(int index) {
            this.index = index;
        }
        public void think(){
            System.out.println("哲学家"+index+"在思考......");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        public void takechop(){
            boolean flag = false;
            int l = index;
            int r = (index+1)%5;
            while(true){
                synchronized (chops[l]){
                    if(chops[l].equals(1)){
                        while(true) {
                            synchronized (chops[r]) {
                                if (chops[r].equals(1)) {
                                    flag = true;
                                } else {
                                    chops[l] = 0;
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                    continue;
                                }
                                break;
                            }
                        }
                        if(flag){
                            chops[l] = 0;
                            chops[r] = 0;
                            break;
                        }
                    }
                }
            }
        }
        public void put(){
            chops[index] = 1;
            chops[(index+1)%5] = 1;
        }
        @Override
        public void run() {
            while(true){
                this.think();
                this.takechop();
                System.out.println("哲学家"+index+"在吃......");
                this.put();
            }
        }
    }
